﻿using System.Configuration;
using System.Web.Mvc;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;

namespace TheDFFL.Web.Controllers
{
    public class BaseController : Controller
    {
        private readonly string consumerKey = ConfigurationManager.AppSettings["OAuthConsumerKey"];
        private readonly string consumerSecret = ConfigurationManager.AppSettings["OAuthConsumerSecret"];

        protected WebConsumer CreateConsumer()
        {
            var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager;

            if (tokenManager == null)
            {
                tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                Session["WcfTokenManager"] = tokenManager;
            }

            var requestTokenEndpoint = new MessageReceivingEndpoint(
                "https://api.login.yahoo.com/oauth/v2/get_request_token",
                HttpDeliveryMethods.GetRequest
            );

            var authorizationEndpoint = new MessageReceivingEndpoint(
                "https://api.login.yahoo.com/oauth/v2/request_auth",
                HttpDeliveryMethods.GetRequest
            );

            var accessTokenEndpoint = new MessageReceivingEndpoint(
                "https://api.login.yahoo.com/oauth/v2/get_token",
                HttpDeliveryMethods.GetRequest
            );

            var consumer = new WebConsumer(
                new ServiceProviderDescription
                {
                    RequestTokenEndpoint = requestTokenEndpoint,
                    UserAuthorizationEndpoint = authorizationEndpoint,
                    AccessTokenEndpoint = accessTokenEndpoint,
                    TamperProtectionElements = new ITamperProtectionChannelBindingElement[]
                    {
					    new HmacSha1SigningBindingElement(),
				    }
                },
                tokenManager
            );

            return consumer;
        }
    }
}
